import SwiftUI

let maxCount = 512
//let maxValue = 120000.0
//let minValue = 100000.0

struct ContentView: View {
    let bluetoothName = ""
    @State var isFingerOn = false
    @State var data = [Double](repeating: 0.0, count: maxCount)
    @State var redData = [Double](repeating: 0.0, count: maxCount)
    @State var heartRate: Int16 = 0
    @State var SPO2: Int16 = 0
    let Bluetooth = BLE()
    var number: UInt32 = 0
    @State var isConnected = false
    let a = Algorithm(sampleRate: 100)
    
    @State var maxValue = 1150000.0
    @State var minValue = 1000000.0
    
    var body: some View {
        VStack(alignment: .center, spacing: 40) {
            HStack(alignment: .top, spacing: 10) {
                VStack {
                    Label { 
                        Text("心率图")
                    } icon: { 
                        Image(systemName: "heart.square.fill")
                    }.font(.largeTitle)
                    
                    LineGraph(data: data, maxData: 60, minValue: minValue, maxValue: maxValue)
                        .clipped()
                        .background(Color.accentColor.opacity(0.1))
                        .cornerRadius(20)
                        .padding()
                        .aspectRatio(1, contentMode: .fit)
                        .frame(width: 480, height: 480, alignment: .center)
                    
                    Text(isFingerOn ? "检测中" : "请把手指放到传感器上")
                }
                .padding(.trailing, 80)
                
                VStack {
                    HStack(alignment: .center, spacing: 30) {
                        VStack {
                            Text("心率")
                                .font(.largeTitle)
                            Text(String(heartRate))
                                .padding()
                                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.accentColor.opacity(0.4)))
                                .font(Font(CTFont(.system, size: 70)))
                            Text("BPM")
                        }
                        VStack {
                            Text("血氧")
                                .font(.largeTitle)
                            Text(String(SPO2))
                                .padding()
                                .background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.accentColor.opacity(0.4)))
                                .font(Font(CTFont(.system, size: 70)))
                            Text("%")
                        }
                    }
                    .padding(.bottom, 20)
                    
                    HStack {
                        Text("最小值：")
                        Slider(value: $minValue, in: 90000.0...120000.0)
                    }.frame(width: 300, height: 40, alignment: .center)
                    
                    HStack {
                        Text("最大值：")
                        Slider(value: $maxValue, in: 105000.0...140000.0)
                    }.frame(width: 300, height: 40, alignment: .center)
                        .padding(.bottom, 35)
                    
                    VStack {
                        Button("连接到心率计") {
                            Bluetooth.startScan()
                            Bluetooth.connectToPeripheral(deviceName: bluetoothName)
                            if (Bluetooth.isConnected) {
                                Bluetooth.stopScan()
                                Bluetooth.scanServices()
                            }
                            isConnected = Bluetooth.isConnected
                        }
                        .padding(.bottom)
                        .buttonStyle(.bordered)
                        .disabled(isConnected)
                        .font(Font(CTFont(.system, size: 24)))
                        
                        Button("断开心率计") {
                            Bluetooth.disconnect()
                            isConnected = false
                            Bluetooth.clearAllDevices()
                        }
                        .padding(.bottom)
                        .buttonStyle(.bordered)
                        .disabled(!isConnected)
                        .font(Font(CTFont(.system, size: 24)))
                    }
                    
                    Button("清空数据") {
                        data = [Double](repeating: 0.0, count: maxCount)
                        heartRate = 0
                        SPO2 = 0
                    }
                    .padding(.bottom)
                    .buttonStyle(.bordered)
                    .font(Font(CTFont(.system, size: 24)))
                }
                .padding(.top, 20)
            }
            
            
        }.onAppear { 
            Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
                isConnected = Bluetooth.isConnected
//                let a = Algorithm(sampleRate: 100)
//                let buf = a.getHRSPO2(IRBuffer: data, RedBuffer: redData)
//                heartRate = buf[0] < 0 ? heartRate : buf[0]
//                SPO2 = buf[1] < 0 ? SPO2 : buf[1]
            }
            // 帧格式：int8    int8        int32  int8  int8
            //       validHR  validSPO2   led     HR   SPO2
            Bluetooth.dataHandler = { buffer in
                if (buffer[0] == 0x00) {
                    let led: UInt32 = (UInt32(buffer[4]) << 24) | (UInt32(buffer[3]) << 16) | (UInt32(buffer[2]) << 8) | UInt32(buffer[1])
                    self.data.append(Double(led))
                    data = Array(data.dropFirst())
                    
                    let red: UInt32 = (UInt32(buffer[8]) << 24) | (UInt32(buffer[7]) << 16) | (UInt32(buffer[6]) << 8) | UInt32(buffer[5])
                    self.redData.append(Double(red))
                    redData = Array(redData.dropFirst())
                    
                    if Double(led) < minValue {
                        let available = led >= 90000 && led <= 120000
                        minValue = available ? Double(led) : minValue
                    }
                    
                    if Double(led) > maxValue {
                        let available = led >= 105000 && led <= 140000
                        maxValue = available ? Double(led) : maxValue
                    }
                }
                else if (buffer[0] == 0x01) {
                    let validHR = buffer[1] == 1
                    let validSPO2 = buffer[2] == 1
                    isFingerOn = validHR && validSPO2
                    let buf = a.getHRSPO2(IRBuffer: data, RedBuffer: redData)
                    if validHR {
                        heartRate = Int16(buffer[3])
                    } else {
                        heartRate = buf[0] < 0 ? heartRate : buf[0]
                    }
                    print(validHR)
                    if validSPO2 {
                        SPO2 = Int16(buffer[4])
                    } else {
                        //SPO2 = -1
                        SPO2 = buf[1] < 0 ? SPO2 : buf[1]
                    }
                }
            }
            //Bluetooth.startScan()
        }
    }
}
